<script lang="ts" setup>
import { computed, onMounted, onUnmounted, ref } from 'vue';
import type { ResourceCardType } from '@/types/micro-scene';
import ResourceCard from './ResourceCard.vue';
import exampleImg from "@/assets/work2.png";
import { useUserStore } from '@/stores/useUserStore';
import { PlusOutlined } from '@ant-design/icons-vue';
import { Modal, type UploadChangeParam, type UploadProps, message } from 'ant-design-vue';
import { addSubstateResource, deleteSubstateResource, getSubstateResources, updateSubstateResourceCoverImage, updateSubstateResourceInfo } from '@/api/MicroScene/MicroSceneSubstateApi';
import { useRoute } from 'vue-router';

const props = defineProps<{
  phaseId: string;
  subPhaseId: string;
}>()

const route = useRoute()
const currentPageIndex = ref<number>(1); // 当前页码
const totalResourceNum = ref<number>(0); // 资源总数
const ResourceCardList = ref<ResourceCardType[]>([]); // 资源列表
const rowCount = 1; // 显示的行数
const colCount = ref<number>(1); // 根据屏幕宽度计算列数
const pageSize = computed(() => rowCount * colCount.value);// 计算每页显示的资源数量

const userStore = useUserStore();
const showEdit = computed(() => {
  return userStore.isEditMicroScene
})

const getColumnCount = () => {
  const width = window.innerWidth;
  if (width >= 1600)
    return 3; // xxl
  if (width >= 1200)
    return 2; // xl
  if (width >= 992)
    return 1; // lg
  if (width >= 768)
    return 1; // md
  if (width >= 576)
    return 1; // sm
  return 1; // xs
};

// 监听屏幕宽度变化，改变colCount
onMounted(() => {
  colCount.value = getColumnCount();
  const handleResize = () => {
    colCount.value = getColumnCount();
  };
  window.addEventListener('resize', handleResize);
  // 组件卸载时移除事件监听
  onUnmounted(() => {
    window.removeEventListener('resize', handleResize);
  });
});

// 计算当前页应该显示的资源
const currentPageResources = computed(() => {
  const start = (currentPageIndex.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return ResourceCardList.value.slice(start, end);
});

// 获取资源数据
const fetchResourceCardMetadata = async () => {
  try {
    const response = await getSubstateResources(Number(route.params.id), Number(props.subPhaseId))
    // 清空ResourceCardList
    ResourceCardList.value = [];
    // 遍历response这个list
    response.forEach((item: any) => {
      const resourceCard: ResourceCardType = {
        resourceId: item.resourceId,
        resourceTitle: item.resourceTitle,
        resourceDescription: item.introduction,
        resourceUrl: item.targetUrl,
        resourceImage: item.coverUrl,
      }
      ResourceCardList.value.push(resourceCard)
    })
    totalResourceNum.value = ResourceCardList.value.length;
  }
  catch (error) {
    message.error('获取资源失败');
  }
};

onMounted(() => {
  fetchResourceCardMetadata();
});

const onPageChangeBtnClicked = (page: number) => {
  currentPageIndex.value = page;
}

// 添加弹窗控制状态
const ismodalVisible = ref(false);
// 判断是否是编辑弹窗
const isEditCard = ref(false);
// 弹窗数据
const formData = ref<ResourceCardType>({
  resourceId: '',
  resourceTitle: '',
  resourceDescription: '',
  resourceUrl: '',
  resourceImage: '',
});
const imageFileList = ref<any[]>([]); // 存图片

// 清空formData和imageFileList
const clearFormDataAndFileList = () => {
  formData.value = {
    resourceId: '',
    resourceTitle: '',
    resourceDescription: '',
    resourceUrl: '',
    resourceImage: '',
  };
  imageFileList.value = [];
}

// 处理图片上传
const handleResourceImageChange = (info: UploadChangeParam) => {
  imageFileList.value = info.fileList;
  // 转化为图片URL
  const fileUrl = URL.createObjectURL(imageFileList.value[0].originFileObj);
  formData.value.resourceImage = fileUrl;
};
const beforeUpload = (file: File) => {
  return false; // 返回 false 阻止上传
};

// 添加一条资源
const AddResource = async (resource: ResourceCardType) => {
  try {
    await addSubstateResource(resource.resourceTitle, resource.resourceDescription, props.subPhaseId, resource.resourceUrl, '', route.params.id as string, imageFileList.value[0].originFileObj)
    fetchResourceCardMetadata();
    message.success('添加资源成功');
  }
  catch (error) {
    message.error('添加资源失败');
  }
  finally {
    clearFormDataAndFileList();
  }
}

// 编辑资源(resourceId不变)
const EditResource = async (resource: ResourceCardType) => {
  try {
    await updateSubstateResourceInfo(Number(route.params.id), Number(resource.resourceId), resource.resourceTitle, resource.resourceDescription, Number(props.subPhaseId), resource.resourceUrl, [])
    // 如果用户修改了图片，则更新图片
    if (imageFileList.value.length > 0 && imageFileList.value[0].uid !== '-1')
      await updateSubstateResourceCoverImage(Number(route.params.id), Number(resource.resourceId), imageFileList.value[0].originFileObj)

    fetchResourceCardMetadata();
    message.success('编辑资源成功');
  }
  catch (error) {
    message.error('编辑资源失败');
  }
  finally {
    clearFormDataAndFileList();
  }
}

const handleShowModal = () => {
  ismodalVisible.value = true;
}

const handleModalCancel = () => {
  ismodalVisible.value = false;
  clearFormDataAndFileList();
}

// 处理弹窗确定
const handleModalOk = () => {
  ismodalVisible.value = false;
  // 编辑
  if (isEditCard.value)
    EditResource(formData.value);

  // 添加
  else
    AddResource(formData.value);
}

// 删除资源入口
const handleDelete = (resourceId: string) => {
  Modal.confirm({
    title: '确定要删除吗？',
    content: '删除后将无法恢复',
    okText: '确定',
    cancelText: '取消',
    onOk: async () => {
      try {
        // 从列表中删除对应的资源
        await deleteSubstateResource(Number(route.params.id), Number(resourceId));
        fetchResourceCardMetadata();
        message.success('删除成功');
      }
      catch (error) {
        message.error('删除失败');
      }
    },
    onCancel: () => {
      return false;
    },
  });
};

// 添加资源入口
const handleAdd = () => {
  isEditCard.value = false;
  handleShowModal();
}

// 编辑资源入口
const handleEdit = (resourceId: string) => {
  isEditCard.value = true;
  // 从列表中找到对应的资源下标
  const index = ResourceCardList.value.findIndex(item => item.resourceId === resourceId);
  // 将resource填充到formData，我不希望绑定formData，而是直接赋值
  formData.value = JSON.parse(JSON.stringify(ResourceCardList.value[index]));
  // 正确设置 fileList
  imageFileList.value = [{
    uid: '-1',
    name: 'image.png',
    status: 'done',
    url: ResourceCardList.value[index].resourceImage,
  }];
  handleShowModal();
}
</script>

<template>
  <div class="flex items-center">
    <div class="text-[0.875rem] font-bold mr-8">
      任务资源
    </div>
    <a-button v-show="showEdit" type="primary" @click="handleAdd">
      添加资源
      <template #icon>
        <PlusOutlined />
      </template>
    </a-button>
  </div>

  <a-layout class="bg-transparent flex flex-col overflow-y-hidden">
    <!-- 模型列表可以滚动区域 -->
    <div class="mx-4 my-4">
      <a-row :gutter="[8, 8]">
        <a-col
          v-for="item in currentPageResources" :key="item.resourceId" :xxl="8" :xl="12" :lg="24" :md="24" :sm="24"
          :xs="24"
        >
          <ResourceCard :resource-card="item" @delete="handleDelete" @edit="handleEdit" />
        </a-col>
      </a-row>
    </div>

    <!-- 底部固定区域 -->
    <div class="flex justify-center">
      <!-- 分页按钮 -->
      <a-pagination
        v-model:current="currentPageIndex" :total="totalResourceNum" :page-size="pageSize"
        :show-size-changer="false" show-quick-jumper :show-total="(total: number) => `共 ${total} 项`" class="self-center"
        @change="onPageChangeBtnClicked"
      />
    </div>
  </a-layout>

  <!-- 添加资源弹窗 -->
  <a-modal
    v-model:open="ismodalVisible" :title="isEditCard ? '编辑资源' : '添加资源'" ok-text="确定" cancel-text="取消"
    :width="600" @ok="handleModalOk" @cancel="handleModalCancel"
  >
    <a-form layout="vertical">
      <div style="display: flex;">
        <div style="margin-top: 20px;">
          <a-upload
            accept="image/*" list-type="picture-card" action="" :before-upload="beforeUpload" :show-upload-list="{
              showPreviewIcon: false,
              showRemoveIcon: true,
            }" :max-count="1" :file-list="imageFileList" @change="handleResourceImageChange"
          >
            <template v-if="imageFileList.length < 1">
              <div style="width: 100px; height: 100px; background-color: #f0f0f0;">
                <PlusOutlined style="margin-top: 30px;" />
                <div style="margin-top: 0;">
                  上传图片
                </div>
              </div>
            </template>
          </a-upload>
        </div>
        <div style="flex: 1; margin-left: 20px;">
          <a-form-item label="资源标题" name="resourceTitle" :rules="[{ required: false, message: '请输入资源标题' }]">
            <a-input v-model:value="formData.resourceTitle" placeholder="请输入资源标题" />
          </a-form-item>
          <a-form-item label="资源链接" name="resourceUrl" :rules="[{ required: false, message: '请输入资源链接' }]">
            <a-input v-model:value="formData.resourceUrl" placeholder="请输入资源链接" />
          </a-form-item>
        </div>
      </div>

      <a-form-item name="resourceDescription" label="资源介绍">
        <a-textarea v-model:value="formData.resourceDescription" placeholder="请输入资源介绍" auto-size />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<style scoped lang="scss"></style>
